package com.takepoints.mobile;

import com.takepoints.android.TPConst;
import com.takepoints.android.bo.MemberProfile;
import com.takepoints.android.services.SecurityServices;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.nfc.NfcAdapter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

public class Takepoints extends BaseActivity {
    
	private GridView grid_main;
	
    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //getWindow().setWindowAnimations(android.R.style.Animation_Translucent);
        
        Integer memberId = getSharedIntValue(TPConst.PRF_MEMBER_ID);
        if(memberId != null && memberId > 0){
        	new ProcessMyPoints().execute(memberId);
        }
		
        grid_main = (GridView)findViewById(R.id.gridMenu);
        grid_main.setAdapter(new ImageAdapter(this));

		String uname = getSharedStringValue(TPConst.PRF_USRNAME);
        if(uname != null && uname.trim().length() > 0){
        	TextView lblHeader = (TextView)findViewById(R.id.lblHeader);
        	lblHeader.setText("ตอนนี้คุณมีคะแนนสะสม");
        }
        manageMenu(1);
    }
    
    public class ImageAdapter extends BaseAdapter {
    	private Context mContext;
		public static final int ACTIVITY_CREATE = 10;
		
		private Integer[] mThumbIds = { R.drawable.menu22, R.drawable.menu12, R.drawable.menu42
										, R.drawable.menu32, R.drawable.menu82, R.drawable.menu62
										, R.drawable.menu52, R.drawable.menu92, R.drawable.menu72 };
		
		private Integer[] mThumbIdsFocus = { R.drawable.menu23, R.drawable.menu13, R.drawable.menu43
										  , R.drawable.menu33, R.drawable.menu83, R.drawable.menu63
										  , R.drawable.menu53, R.drawable.menu93, R.drawable.menu73 };
		
		public ImageAdapter(Context c){
			mContext = c;
		}
		
		@Override
		public int getCount(){
			return mThumbIds.length;
		}
		
		public View getView(final int position, View convertView, ViewGroup parent){
			 final ImageView imageView;
			 if(convertView == null){
				 imageView = new ImageView(mContext);
				 
				 int density = getResources().getDisplayMetrics().densityDpi;
				 if(density >= DisplayMetrics.DENSITY_XHIGH){
					 imageView.setLayoutParams(new GridView.LayoutParams(195, 195));
				 } else if(density >= DisplayMetrics.DENSITY_HIGH){
					 imageView.setLayoutParams(new GridView.LayoutParams(130, 130));
				 } else if(density >= DisplayMetrics.DENSITY_MEDIUM){
					 imageView.setLayoutParams(new GridView.LayoutParams(87, 87));
				 } else{		// DisplayMetrics.DENSITY_LOW
					 imageView.setLayoutParams(new GridView.LayoutParams(52, 52));
				 }
				 
				 imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
				 imageView.setPadding(2, 2, 2, 2);
			 } else{
				 imageView = (ImageView)convertView;
			 }
			 imageView.setImageResource(mThumbIds[position]);
			 imageView.setOnTouchListener(new View.OnTouchListener(){
				 public boolean onTouch(View v, MotionEvent event){
					 int action = event.getAction();
					 switch(action){
					 	case MotionEvent.ACTION_DOWN:
					 		imageView.setImageResource(mThumbIdsFocus[position]);
					 		break;
					 	case MotionEvent.ACTION_UP:
					 		imageView.setImageResource(mThumbIds[position]);
					 		break;
					 	case MotionEvent.ACTION_MOVE:
					 		imageView.setImageResource(mThumbIds[position]);
					 		break;
					 	case MotionEvent.ACTION_CANCEL:
					 		imageView.setImageResource(mThumbIds[position]);
					 		break;
					 	default:
					 		break;
					 }
					 return false;
				}
			 });
			 if(R.drawable.menu12 == mThumbIds[position]){
				 imageView.setOnClickListener(new View.OnClickListener(){
					 public void onClick(View view) {
						 Intent offersInt = new Intent(view.getContext(), TPOffers.class);
						 offersInt.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						 startActivityForResult(offersInt, 0);
					}
				 });
			 } else if(R.drawable.menu22 == mThumbIds[position]){
				 imageView.setOnClickListener(new View.OnClickListener(){
					 public void onClick(View view) {
						 Intent cardsInt = new Intent(view.getContext(), TPCards.class);
						 cardsInt.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						 startActivityForResult(cardsInt, 0);
					 }
				 });
			 } else if(R.drawable.menu32 == mThumbIds[position]){
				 imageView.setOnClickListener(new View.OnClickListener(){
					 public void onClick(View view) {
						Intent nearByInt = new Intent(view.getContext(), NearBy.class);
						nearByInt.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    	    			nearByInt.putExtra(TPConst.LOCATE_TYPE, TPConst.LOCATE_TYPE_NEAR_BY);
						startActivity(nearByInt);
					 }
				 });
			 } else if(R.drawable.menu42 == mThumbIds[position]){
				 imageView.setOnClickListener(new View.OnClickListener(){
					 public void onClick(View view) {
						 Intent rewardsInt = new Intent(view.getContext(), TPRewards.class);
						 rewardsInt.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						 startActivityForResult(rewardsInt, 0);
					 }
				 });
			 } else if(R.drawable.menu52 == mThumbIds[position]){
				 imageView.setOnClickListener(new View.OnClickListener(){
					 public void onClick(View view) {
						 if(getSharedIntValue(TPConst.PRF_MEMBER_ID) < 1){
							 confirmLoginDlg();
						 } else{
							 Intent myProfileInt = new Intent(view.getContext(), MyProfile.class);
							 myProfileInt.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							 startActivityForResult(myProfileInt, 0);
						 }
					 }
				 });
			 } else if(R.drawable.menu62 == mThumbIds[position]){
				 imageView.setOnClickListener(new View.OnClickListener(){
					 public void onClick(View view) {
						 if(getSharedIntValue(TPConst.PRF_MEMBER_ID) < 1){
							 confirmLoginDlg();
						 } else{
								PackageManager pckMng = getPackageManager();
								if (pckMng != null && pckMng.hasSystemFeature(PackageManager.FEATURE_NFC)) {
								 processCheckIn(view.getContext());
							 } else{
								 alert("ไม่สามารถ Check-In ได้ !\n\n เนื่องจากมือถือของคุณ..ไม่รองรับ NFC");
							 }
						 }
					}
				 });
			 } else if(R.drawable.menu72 == mThumbIds[position]){
				 imageView.setOnClickListener(new View.OnClickListener(){
					 public void onClick(View view) {
						 Intent settingInt = new Intent(view.getContext(), Setting.class);
						 startActivityForResult(settingInt, 0);
					}
				 });
			 } else if(R.drawable.menu82 == mThumbIds[position]){
				 imageView.setOnClickListener(new View.OnClickListener(){
					 public void onClick(View view) {
						 //popup("Takepoints.com");
						 Intent intent = new Intent(view.getContext(), TPDeals.class);
						 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						 startActivityForResult(intent, 0);
					}
				 });
			 } else if(R.drawable.menu92 == mThumbIds[position]){
				 imageView.setOnClickListener(new View.OnClickListener(){
					 public void onClick(View view) {
						 Intent intent = new Intent(view.getContext(), TPEventNews.class);
						 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						 startActivityForResult(intent, 0);
					}
				 });
			 }
			 return imageView;
		}
		
		@Override
		public Object getItem(int arg0){
			return null;
		}
		
		@Override
		public long getItemId(int position){
			return position;
		}
	}
    
    @TargetApi(10)
    private void processCheckIn(Context ctx){
    	NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter();
		 if(nfcAdapter.isEnabled()){
			 Intent nfcChkInInt = new Intent(ctx, NfcCheckin.class);
			 nfcChkInInt.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			 startActivityForResult(nfcChkInInt, 0);
		 } else{
			 confirmNetworkSetting();
		 }
    }

    @TargetApi(10)
    private void confirmNetworkSetting(){
		final AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
		//alertbox.setMessage("NFC is disabled !\n\nDo you want to enable NFC ?");
		alertbox.setMessage("NFC ถูกปิดอยู่ !\n\nคุณต้องการเปิด NFC ใช่หรือไม่ ?");
		alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dlgInf, int which) {
				gotoNetworkSetting();
			}
		});
		alertbox.setNeutralButton("No", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dlgInf, int which) {
				dlgInf.dismiss();
			}
		});
		alertbox.show();
	}
    private final void gotoNetworkSetting(){
    	startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
    }
    
    class ProcessMyPoints extends AsyncTask<Integer, Void, MemberProfile>{
    	@Override
        protected void onPreExecute(){
            super.onPreExecute();
    	}
    	
    	@Override
        protected MemberProfile doInBackground(Integer... params){
    		return SecurityServices.getMyInfo(params[0]);
    	}
    	
    	@Override
        protected void onPostExecute(MemberProfile profile){
    		if(profile != null){
    			//RelativeLayout layMyPoints = (RelativeLayout)findViewById(R.id.layMyPoints);
    			//layMyPoints.setVisibility(View.VISIBLE);
    			
    			//TextView txtMyPoints = (TextView)findViewById(R.id.txtMyPoints);
    			//txtMyPoints.setText("คุณมี " + profile.getRedeemPoint() + " คะแนน !!!");
    			
    			TextView lblPoints = (TextView)findViewById(R.id.lblPoints);
    			lblPoints.setText( profile.getRedeemPoint() );
    		}
    	}
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event){
        if(keyCode == KeyEvent.KEYCODE_BACK){
            moveTaskToBack(true);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    
}
